import * as React from 'react';
import { Badge, Button } from 'antd';
import 'react-dragula/dist/dragula.css';
import './PopToSort.scss';
import CustomModal from 'components/common/CustomModal';

const Dragula = require('react-dragula');

interface SortProps {
  items: any[];
  sortName: string;
  onCancel: () => any;
  onOk: (data: any[]) => any;
}
interface SortState {
  isDragging: boolean;
  sortedIds: number[];
}

// [ { id, name }, ... ]
// 返回排序后的id数组 [1, 2, 3, ...]
class PopToSort extends React.Component<SortProps, SortState> {
  dragulaHandle: any;
  initSequence: string;
  static defaultProps: SortProps = {
    items: [],
    sortName: '',
    onCancel: () => {},
    onOk: () => {},
  };
  constructor(props: SortProps) {
    super(props);

    this.dragulaHandle = null;
    this.state = {
      isDragging: false,
      sortedIds: [],
    };

    const indexes = [];
    for (let i = 0; i < props.items.length; i++) {
      indexes.push(i);
    }
    this.initSequence = indexes.join(',');
  }

  listenDrag() {
    if (this.dragulaHandle) {
      this.dragulaHandle.on('drag', () => {
        this.setState({
          isDragging: true,
        });
      });

      this.dragulaHandle.on('dragend', () => {
        const nodeLists = this.dragulaHandle.containers[0].childNodes;
        const nodeAmount = nodeLists.length;
        const sortedIds = [];

        for (let index = 0; index < nodeAmount; index += 1) {
          sortedIds.push(Number(nodeLists[index].id));
        }

        this.setState({
          isDragging: false,
          sortedIds,
        });
      });
    }
  }

  componentWillUnmount() {
    if (this.dragulaHandle) {
      this.dragulaHandle.destroy();
    }
  }

  handleSubmit = () => {
    const { onOk } = this.props;
    const { sortedIds } = this.state;

    onOk(sortedIds);
  };

  handleClose = () => {
    this.props.onCancel();
  };

  dragulaDecorator = (Wrapper: any) => {
    this.dragulaHandle = Dragula([Wrapper], {
      direction: 'vertical',
      // elements are moved by default, not copied
      copy: false,
      // elements in copy-source containers can be reordered
      copySortSource: false,
    });

    this.listenDrag();
  };

  render() {
    const { items, sortName } = this.props;
    const { sortedIds } = this.state;
    const hasChanged = sortedIds.length && sortedIds.join(',') !== this.initSequence;

    return (
      <CustomModal
        title={sortName}
        className="popup-to-sort"
        width={500}
        footer={[
          <Button key="back" type="ghost" size="large" onClick={this.handleClose}>
            取消
          </Button>,
          <Button
            disabled={!hasChanged}
            key="submit"
            type="primary"
            size="large"
            onClick={this.handleSubmit}>
            保存
          </Button>,
        ]}>
        <div ref={this.dragulaDecorator} className="sort-item-wrapper">
          {items.map((item: any, index: number) => {
            return (
              <div id={item.id} key={index} className="sort-item">
                <Badge count={index + 1} />
                &nbsp;{item['name']}
              </div>
            );
          })}
        </div>
      </CustomModal>
    );
  }
}

export default PopToSort;
